package com.bell.atensettings.wifi;

import static android.net.wifi.WifiConfiguration.INVALID_NETWORK_ID;
import java.net.InetAddress;
import java.util.Iterator;

import com.bell.atensettings.R;
import com.bell.atensettings.bean.AccessPoint;

import android.content.Context;
import android.content.res.Resources;
import android.media.MediaRouter.RouteInfo;
import android.net.LinkAddress;
import android.net.LinkProperties;
import android.net.NetworkInfo.DetailedState;
import android.net.NetworkUtils;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.AuthAlgorithm;
import android.net.wifi.WifiConfiguration.IpAssignment;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.wifi.WifiConfiguration.ProxySettings;
import android.net.wifi.WifiInfo;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

public class WifiConfigController implements TextWatcher
{
    private static final String KEYSTORE_SPACE = WifiConfiguration.KEYSTORE_URI;
    private static final String PHASE2_PREFIX = "auth=";

    private final WifiConfigUiBase mConfigUi;
    private final View mView;
    private final AccessPoint mAccessPoint;

    private boolean mEdit;

    private TextView mSsidView;

    // e.g. AccessPoint.SECURITY_NONE
    private int mAccessPointSecurity;
    private TextView mPasswordView;

    private TextView mEapIdentityView;
    private TextView mEapAnonymousView;

    /* This value comes from "wifi_ip_settings" resource array */
    private static final int DHCP = 0;
    private static final int STATIC_IP = 1;

    /* These values come from "wifi_proxy_settings" resource array */
    public static final int PROXY_NONE = 0;
    public static final int PROXY_STATIC = 1;

    /* These values from from "wifi_eap_method" resource array */
    public static final int WIFI_EAP_METHOD_PEAP = 0;
    public static final int WIFI_EAP_METHOD_TLS = 1;
    public static final int WIFI_EAP_METHOD_TTLS = 2;
    public static final int WIFI_EAP_METHOD_PWD = 3;

    private static final String TAG = "WifiConfigController";

//    private Spinner mIpSettingsSpinner;

    private IpAssignment mIpAssignment = IpAssignment.UNASSIGNED;
    private LinkProperties mLinkProperties = new LinkProperties();

//    private final Handler mTextViewChangedHandler;

    static boolean requireKeyStore(WifiConfiguration config)
    {
        if (config == null) {
            return false;
        }
        if (!TextUtils.isEmpty(config.key_id.value())) {
            return true;
        }
        String values[] = { config.ca_cert.value(), config.client_cert.value() };
        for (String value : values) {
            if (value != null && value.startsWith(KEYSTORE_SPACE)) {
                return true;
            }
        }
        return false;
    }

    public WifiConfigController(WifiConfigUiBase parent, View view, AccessPoint accessPoint, boolean edit) 
    {
        mConfigUi = parent;

        mView = view;
        mAccessPoint = accessPoint;
        mAccessPointSecurity = (accessPoint == null) ? AccessPoint.SECURITY_NONE : accessPoint.security;
        mEdit = edit;

//        mTextViewChangedHandler = new Handler();
        final Context context = mConfigUi.getContext();
        final Resources resources = context.getResources();

        // mIpSettingsSpinner = (Spinner) mView.findViewById(R.id.ip_settings);
        // mIpSettingsSpinner.setOnItemSelectedListener(this);

        mConfigUi.setTitle(mAccessPoint.ssid);

        ViewGroup group = (ViewGroup) mView.findViewById(R.id.info);

        DetailedState state = mAccessPoint.getState();
        if (state != null) {
            addRow(group, R.string.wifi_status, mAccessPoint.getStateString( state));
        }

        int level = mAccessPoint.getLevel();
        if (level != -1) {
            String[] signal = resources.getStringArray(R.array.wifi_signal);
            addRow(group, R.string.wifi_signal, signal[level]);
        }

        WifiInfo info = mAccessPoint.getInfo();
        if (info != null && info.getLinkSpeed() != -1) {
            addRow(group, R.string.wifi_speed, info.getLinkSpeed() + WifiInfo.LINK_SPEED_UNITS);
        }

        addRow(group, R.string.wifi_security, mAccessPoint.getSecurityString(false));

        boolean showAdvancedFields = false;
        if (mAccessPoint.getNetworkId() != INVALID_NETWORK_ID) {
            WifiConfiguration config = mAccessPoint.getConfig();
            // Display IP addresses
            for (InetAddress a : config.linkProperties.getAddresses()) {
                addRow(group, R.string.wifi_ip_address, a.getHostAddress());
            }
        }

        // if (mEdit) {
        // mConfigUi.setSubmitButton(context.getString(R.string.wifi_save));
        // } else {
        if (state == null && level != -1) {
            mConfigUi.setSubmitButton(context.getString(R.string.wifi_connect));
        } 

        if (mAccessPoint.getNetworkId() != INVALID_NETWORK_ID) {
            mConfigUi.setForgetButton(context.getString(R.string.wifi_forget));
        }

        mConfigUi.setCancelButton(context.getString(R.string.wifi_cancel));
    }

    private void addRow(ViewGroup group, int name, String value)
    {
        View row = mConfigUi.getLayoutInflater().inflate(R.layout.wifi_dialog_row, group, false);
        ((TextView) row.findViewById(R.id.name)).setText(name);
        ((TextView) row.findViewById(R.id.value)).setText(value);
        group.addView(row);
    }

    /* show submit button if password, ip and proxy settings are valid */
    void enableSubmitIfAppropriate()
    {
        Button submit = mConfigUi.getSubmitButton();
        if (submit == null)
            return;

        boolean enabled = false;
        boolean passwordInvalid = false;

        if (mPasswordView != null
                && ((mAccessPointSecurity == AccessPoint.SECURITY_WEP 
                && mPasswordView.length() == 0) 
                || (mAccessPointSecurity == AccessPoint.SECURITY_PSK 
                && mPasswordView.length() < 8))) {
            passwordInvalid = true;
        }

        if ((mSsidView != null && mSsidView.length() == 0)
                || ((mAccessPoint == null || mAccessPoint.getNetworkId() == INVALID_NETWORK_ID) && passwordInvalid)) {
            enabled = false;
        } else {
            if (ipAndProxyFieldsAreValid()) {
                enabled = true;
            } else {
                enabled = false;
            }
        }
        submit.setEnabled(enabled);
    }

    /* package */WifiConfiguration getConfig()
    {
        if (mAccessPoint != null && mAccessPoint.getNetworkId() != INVALID_NETWORK_ID && !mEdit) {
            return null;
        }

        WifiConfiguration config = new WifiConfiguration();

        if (mAccessPoint == null) {
            config.SSID = AccessPoint.convertToQuotedString(mSsidView.getText().toString());
            // If the user adds a network manually, assume that it is hidden.
            config.hiddenSSID = true;
        } else if (mAccessPoint.getNetworkId() == INVALID_NETWORK_ID) {
            config.SSID = AccessPoint.convertToQuotedString(mAccessPoint.ssid);
        } else {
            config.networkId = mAccessPoint.getNetworkId();
        }

        switch (mAccessPointSecurity) {
            case AccessPoint.SECURITY_NONE:
                config.allowedKeyManagement.set(KeyMgmt.NONE);
                break;

            case AccessPoint.SECURITY_WEP:
                config.allowedKeyManagement.set(KeyMgmt.NONE);
                config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
                config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
                if (mPasswordView.length() != 0) {
                    int length = mPasswordView.length();
                    String password = mPasswordView.getText().toString();
                    // WEP-40, WEP-104, and 256-bit WEP (WEP-232?)
                    if ((length == 10 || length == 26 || length == 58) && password.matches("[0-9A-Fa-f]*")) {
                        config.wepKeys[0] = password;
                    } else {
                        config.wepKeys[0] = '"' + password + '"';
                    }
                }
                break;

            case AccessPoint.SECURITY_PSK:
                config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
                if (mPasswordView.length() != 0) {
                    String password = mPasswordView.getText().toString();
                    if (password.matches("[0-9A-Fa-f]{64}")) {
                        config.preSharedKey = password;
                    } else {
                        config.preSharedKey = '"' + password + '"';
                    }
                }
                break;

            case AccessPoint.SECURITY_EAP:
                config.allowedKeyManagement.set(KeyMgmt.WPA_EAP);
                config.allowedKeyManagement.set(KeyMgmt.IEEE8021X);
                config.identity.setValue((mEapIdentityView.length() == 0) ? "" : mEapIdentityView.getText().toString());
                config.anonymous_identity.setValue((mEapAnonymousView.length() == 0) ? "" : mEapAnonymousView.getText()
                        .toString());
                if (mPasswordView.length() != 0) {
                    config.password.setValue(mPasswordView.getText().toString());
                }
                break;

            default:
                return null;
        }

        //config.proxySettings = mProxySettings;
        config.ipAssignment = mIpAssignment;
        config.linkProperties = new LinkProperties(mLinkProperties);

        return config;
    }

    private boolean ipAndProxyFieldsAreValid()
    {
//        mLinkProperties.clear();
//        mIpAssignment = (mIpSettingsSpinner != null && mIpSettingsSpinner.getSelectedItemPosition() == STATIC_IP) ? IpAssignment.STATIC
//                : IpAssignment.DHCP;

//        if (mIpAssignment == IpAssignment.STATIC) {
//            int result = validateIpConfigFields(mLinkProperties);
//            if (result != 0) {
//                return false;
//            }
//        }

//        mProxySettings = (mProxySettingsSpinner != null && mProxySettingsSpinner.getSelectedItemPosition() == PROXY_STATIC) ? ProxySettings.STATIC
//                : ProxySettings.NONE;
//
//        if (mProxySettings == ProxySettings.STATIC && mProxyHostView != null) {
//            String host = mProxyHostView.getText().toString();
//            String portStr = mProxyPortView.getText().toString();
//            String exclusionList = mProxyExclusionListView.getText().toString();
//            int port = 0;
//            int result = 0;
//            try {
//                port = Integer.parseInt(portStr);
//                result = ProxySelector.validate(host, portStr, exclusionList);
//            } catch (NumberFormatException e) {
//                result = R.string.proxy_error_invalid_port;
//            }
//            if (result == 0) {
//                ProxyProperties proxyProperties = new ProxyProperties(host, port, exclusionList);
//                mLinkProperties.setHttpProxy(proxyProperties);
//            } else {
//                return false;
//            }
//        }
        return true;
    }

    public boolean isEdit()
    {
        return mEdit;
    }

    @Override
    public void afterTextChanged(Editable s)
    {
//        mTextViewChangedHandler.post(new Runnable() {
//            public void run()
//            {
//                enableSubmitIfAppropriate();
//            }
//        });
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after)
    {
        // work done in afterTextChanged
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count)
    {
        // work done in afterTextChanged
    }
}
